<template>
	<view class="page-live" @touchmove.stop="">
		<!-- #ifdef MP-WEIXIN -->
		<go-back />
		<view class="live-header" :style="{height: Custom?`${Custom.height}px`:'50rpx',top:Custom?`${Custom.top}px`:'20rpx'}">
			<view class="avatar">
				<image :src="liveInfo.avatar" style="width: 100%;height:100%;border-radius: 50%;" />
			</view>
			<view class="flex flex-direction padding-lr" height="50rpx">
				<view style="font-size: 20rpx;">
					<text>{{liveInfo.nickname}}</text>
				</view>
				<view style="font-size: 20rpx;color:#343436">
					<text>{{client_total}}人</text>
				</view>
			</view>
			<view>
				<view class="cu-btn round bg-red" style="height:50rpx;" @click="handleUnAttention(liveInfo.user_id,index)" v-if="!!liveInfo.is_attention">
					取消关注
				</view>
				<view class="cu-btn round bg-red" style="height:50rpx;" @click="handleAttention(liveInfo.user_id,index)" v-else>
					关注
				</view>
			</view>
		</view>
		<!-- #endif -->
		<live-player :src="liveInfo.play_url" :autoplay="true" object-fit="fillCrop" @statechange="statechange" @error="error"
		 style="width: 100vw; height: 100%;" />
		<!-- 弹幕 -->
		<view class="live-wrap padding">
			<scroll-view scroll-y :scroll-top="scrollTop" id="msg" class="msg-wrap">
				<block v-for="(item,index) of client_msg_list" :key="index">
					<!-- 进入直播间 -->
					<view class="tip msg-item" v-if="item.type===1">
						<view class="bg-red text-white padding-xs tip-cont">
							<text>{{item.content}}</text>
						</view>
					</view>
					<!-- 打赏 -->
					<view class="tip msg-item" v-if="item.type===4">
						<view class="bg-red text-white padding-xs tip-cont">
							<text>{{item.content}}</text>
						</view>
					</view>
					<!-- 发送消息 -->
					<view class="live-cont msg-item">
						<view class="live-cont-item padding-lr-xs" v-if="item.type===2">
							<text class="text-red">{{item.name}}</text>
							<text class="margin-left-xs">{{item.content}}</text>
						</view>
						<view class="live-cont-item padding-lr-xs" v-if="item.type===3">
							<text class="text-red">公告：</text><text>{{item.content}}</text>
						</view>
					</view>
				</block>
			</scroll-view>
		</view>


		<view class="chat padding" :style="{bottom:`${InputBottom}px`}">
			<view class="chat-left">
				<view class="chat-left-item" @click="handleShowPopup('showPayPopup')">
					<image src="@/static/icons/live-reward.png" />
					<text>打赏</text>
				</view>
			</view>
			<view class="chat-cont padding">
				<view style="border-bottom: 2rpx solid #fff;padding:6rpx 0">
					<input placeholder="跟主播聊点什么" placeholder-class="text-sm" maxlength="50" :adjust-position="false" @focus="InputFocus"
					 @blur="InputBlur" v-model="content" @confirm="handleSend" confirm-type="send" />
				</view>
			</view>
			<view class="chat-right">
				<view class="chat-right-item" @click="handleMore">
					<image src="@/static/icons/live-share.png" />
					<text>分享</text>
				</view>
				<view class="chat-right-item" @click="handleLike">
					<image src="@/static/icons/live-like.png" v-if="liveInfo.is_like===1" />
					<image src="@/static/icons/live-unlike.png" v-else />
					<text>赞</text>
				</view>
			</view>
		</view>
		<!-- 海报 -->
		<my-poster ref="hchPoster" :canvasFlag.sync="canvasFlag" :posterObj.sync="posterData" />
		<!-- 尚未开始 -->
		<h-popup :show.sync="showPopup">
			<view class="title-popup-wrap" style="padding:40rpx 20rpx">
				<view style="margin-top: 60rpx;">
					<text style="font-size: 32rpx;">— 直播尚未开始 —</text>
				</view>
				<view class="flex flex-direction margin-top-sm" style="color:#999999;font-size: 32rpx;">
					<text>
						直播时间
					</text>
					<text>
						2020-07-05 18:00
					</text>
				</view>
				<view class="flex justify-center align-center" style="margin-top:100rpx">
					<image src="../../static/icons/live-warning.png" style="width:44rpx;height:44rpx" />
				</view>
				<view class="flex flex-direction margin-top-sm" style="font-size: 28rpx;">
					<text>右上角关注直播</text>
					<text>开播会给您发送提醒</text>
				</view>
			</view>
		</h-popup>

		<!-- 自定义打赏金额 -->
		<h-popup :show.sync="showPayTextPopup" v-if="showPayTextPopup">
			<view class="padding bg-white">
				<view class="cu-form-group margin-top-xs">
					<input name="input" placeholder="输入金额" placeholder-style="color:#ccc" v-model="total_price" />
				</view>
				<view class="btn-wrap margin-top-sm" style="width:100%;display: flex;justify-content: center;">
					<button class="cu-btn round bg-red" style="width:200rpx" @click="handlePay">提交</button>
				</view>
			</view>
		</h-popup>


		<!-- 打赏 -->

		<h-popup type="bottom-modal" :show.sync="showPayPopup">
			<view class="padding" style="background-color: #fff;">
				<h-multi-tags title="选择打赏金额" :list.sync="payList" labelKey="value" valueKey="value" :value.sync="total_price" type="radio" />
				<view class="btn-wrap margin-top-sm padding-lr">
					<button class="cu-btn round" style="background-color: #000;width: 200rpx;" @click="handleCreate">自定义</button>
					<button :class="['cu-btn','round','bg-red','animation',animationType]" style="width:340rpx" @click="handlePay">立即打赏</button>
				</view>
			</view>
		</h-popup>

		<!-- 底部分享选择框 -->
		<h-popup type="bottom-modal" :show.sync="showSharePopup">
			<view class="share padding">
				<view class="share-item padding-sm" @click="createPoster">
					生成海报
				</view>
				<view class="share-item padding-sm" style="width:100%;border-top:1px solid #eee;border-bottom: 1px solid #eee;">
					<button class="cu-btn" open-type="share" style="width:100%;background:transparent">
						分享好友
					</button>
				</view>
				<view class="share-item padding-sm" @click="handleHidePopup('showSharePopup')">
					取消
				</view>
			</view>
		</h-popup>
	</view>
</template>

<script>
	import HPopup from '@/components/HPopup'
	import MyPoster from '@/components/MyPoster'
	import HMultiTags from "@/components/HMultiTags"
	export default {
		data() {
			return {
				id: 0,
				TabCur: 0,
				tabList: ['关注', '推荐', '分类', '分类分类分类', '分类'],
				liveInfo: {},
				posterData: {},
				canvasFlag: true,
				showPopup: false,
				showPayPopup: false,
				showPayTextPopup: false,
				showSharePopup: false,
				payList: [{
						value: "1元"
					},
					{
						value: "2元"
					},
					{
						value: "5元"
					},
					{
						value: "10元"
					},
					{
						value: "20元"
					},
					{
						value: "100元"
					},
				],
				total_price: "",
				content: "", //消息内容
				client_total: 0, //人数
				client_msg_list: [], //当前在线消息数据
				scrollTop: 0,
				InputBottom: 0,
				live_status: 1,
				hasToasted: false, //是否已经提示过
			};
		},
		components: {
			HPopup,
			MyPoster,
			HMultiTags
		},
		methods: {
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			statechange(e) {
				console.log("statechange:" + JSON.stringify(e));
			},
			error(e) {
				console.log("error:" + JSON.stringify(e));
			},
			tabSelect(index) {
				this.TabCur = index
			},
			handleShowPopup(key) {
				this[key] = !this[key]
			},
			handleHidePopup(key) {
				this[key] = false
			},
			handleCreate() {
				this.handleShowPopup('showPayPopup')
				this.handleShowPopup('showPayTextPopup')
			},
			async handleLike() {
				let is_like = this.liveInfo.is_like
				let query = {
					id: this.liveInfo.id
				}
				if (is_like === 1) {
					let {
						code
					} = await this.$h.api.liveModel.postLiveUnLike(query)
					if (code === 1) {
						this.$h.toast('取消点赞')
						this.$set(this.liveInfo, 'is_like', 0)
					}
				} else {
					let {
						code
					} = await this.$h.api.liveModel.postLiveLike(query)
					console.log("code", code)
					if (code === 1) {
						this.$h.toast('点赞成功', true)
						this.$set(this.liveInfo, 'is_like', 1)
					}
				}
			},
			async handlePay() {
				// 弹出框消失
				this.showPayPopup = false
				this.showPayTextPopup = false
				if (this.total_price.indexOf('元') > 0) {
					this.total_price = this.total_price.slice(0, -1)
				}
				let {
					code,
					data
				} = await this.$h.api.payModel.postPay({
					total_price: +this.total_price,
					id: this.id,
					user_id: this.liveInfo.user_id
				})
				if (code === 1) {
					let {
						timeStamp,
						nonceStr,
						signType,
						paySign
					} = data
					this.$h.lib.pay({
						timeStamp: timeStamp.toString(),
						nonceStr,
						Package: data.package,
						signType,
						paySign,
					}).then(res => {
						this.$h.toast("支付成功", true)
						let query = {
							type: "reward",
							room_id: this.id, //房间Id
							client_name: this.userInfo.nickname, //用户昵称
							nickname: this.liveInfo.nickname, //主播昵称
							total_fee: +this.total_price //总金额
						}
						this.$h.wb.send(JSON.stringify(query)).then(res => {
							this.content = "" //发送成功后，清除聊天记录
						})
					}).catch(err => {
						console.log(err)
					})
				}
			},
			handleMore() {
				this.handleShowPopup('showSharePopup')
			},
			//生成海报
			async createPoster() {
				this.handleHidePopup('showSharePopup')
				let query = {
					id: this.liveInfo.id,
					type: "live"
				}
				let {
					data,
					code
				} = await this.$h.api.codeModel.getWXCode(query)
				if (code === 1) {
					let {
						avatar,
						title,
						head_img,
						code_img,
						nickname
					} = data.data
					this.canvasFlag = false
					Object.assign(this.posterData, {
						avatar,
						url: head_img, //商品主图
						title, //标题
						userInfo: nickname,
						subTitle: "我刚分享了",
						code: code_img, //小程序码
					})
					this.$nextTick(function() {
						this.$refs.hchPoster.createCanvasImage(); //调用子组件的方法
					})
				}
			},
			async getLiveInfo() {
				let query = {
					id: this.id
				}
				let {
					data
				} = await this.$h.api.liveModel.getLiveDetail(query)
				this.liveInfo = data
			},
			initConnect() {
				this.$h.wb.initConect().then(res => {
					if (res) {
						this.onMsg()
						this.handleConnect()
					} else {
						this.initConnect()
					}
				})
			},
			handleConnect() {
				let query = {
					type: "login",
					client_name: this.userInfo.nickname,
					room_id: this.id
				}
				//创建websocket房间链接
				this.$h.wb.send(JSON.stringify(query)).then(res => {
					console.log(res)
				})
			},
			//发送信息
			handleSend() {
				let query = {
					type: "say",
					to_client_id: "all",
					to_client_name: this.userInfo.nickname,
					content: this.content
				}
				this.$h.wb.send(JSON.stringify(query)).then(res => {
					this.content = "" //发送成功后，清除聊天记录
				})
			},
			//添加信息到视图
			handleAppend(item) {
				this.client_msg_list.push(item)
				//自动滚动到最底部
				this.scrollToBottom()
			},
			scrollToBottom() {
				this.$nextTick(function() {
					const query = uni.createSelectorQuery().in(this);
					let that = this
					let scrollHeight = 0
					query.selectAll('.msg-item').boundingClientRect(res => {
						res.forEach(rect => scrollHeight += rect.height)
						that.scrollTop = scrollHeight
					}).exec();
				})
			},
			//接受websocket的信息
			onMsg() {
				this.$h.wb.socketTask.onMessage(e => {
					var data = JSON.parse(e.data);
					console.log("on", data)
					switch (data.type) {
						// 服务端ping客户端
						case 'ping':
							this.$h.wb.send('{"type":"pong"}');
							break;
							// 登录 更新用户列表
						case 'login':
							this.handleAppend({
								type: 1,
								content: data.client_name + "进入直播间"
							});
							break;
							// 发言
						case 'say':
							this.handleAppend({
								type: 2,
								name: data.from_client_name,
								content: data.content
							})
							break;
							// 用户离开 更新用户列表
						case 'logout':
							// this.handleAppend({
							// 	type: 1,
							// 	content: data.from_client_name + "离开了直播间",
							// })
							break;
						case 'living':
							this.client_total = data.play_num;
							break;
						case 'live_status':
							this.live_status = data.status;
							this.checkLiveStatus()
							break;
						case 'reward':
							this.handleAppend({
								type: 4,
								content: data.content
							})
							break;
					}
				})
			},
			checkLiveStatus() {
				if (this.hasToasted) {
					return
				}
				if (this.live_status != 1) {
					this.hasToasted = true
					this.$h.toast("直播已关闭").then(()=>{
						this.$h.router.back()
					})
				}
			},
			async handleAttention(attention_user_id) {
				let query = {
					attention_user_id
				}
				let {
					code
				} = await this.$h.api.userModel.postLike(query)
				if (code === 1) {
					this.$set(this.liveInfo, 'is_attention', 1)
				}
			},
			async handleUnAttention(attention_user_id) {
				let query = {
					attention_user_id
				}
				let {
					code
				} = await this.$h.api.userModel.postUnLike(query)
				if (code === 1) {
					this.$set(this.liveInfo, 'is_attention', 0)
				}
			},
		},
		onLoad({
			id
		}) {
			this.id = id
			this.initConnect()
			this.getLiveInfo()
		},
		beforeDestroy() {
			if (this.$h.wb.status === 'open') {
				this.$h.wb.closeConnect()
			}
		},
		onShow() {
			//屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			})
		},
		//分享
		onShareAppMessage() {
			let query = {
				id: this.liveInfo.id
			}
			this.$h.api.liveModel.postShareLive(query)
			this.handleHidePopup('showSharePopup')
			return {
				title: this.liveInfo.title,
				imageUrl: this.liveInfo.img,
				path: `/pages/home/home?type=share_live&id=${this.liveInfo.id}`
			}
		},
	}
</script>
<style>
	page {
		height: 100%;
	}
</style>
<style lang="scss" scoped>
	.page-live {
		width: 100vw;
		height: 100vh;
		background: #000;

		.live-header {
			position: fixed;
			left: 100rpx;
			z-index: 1000;
			// width: 320rpx;
			padding: 6rpx;
			box-sizing: border-box;
			background: #fff;
			border-radius: 15px;

			@include df-row($jc: space-between, $ai:center) .avatar {
				width: 50rpx;
				height: 50rpx;
			}
		}

		.live-wrap {
			height: 350rpx;
			position: fixed;
			left: 0;
			bottom: 200rpx;

			.msg-wrap {
				height: 100%;
				@include df-col()
			}

			.tip {
				min-width: 166rpx;
				margin-bottom: 10rpx;

				&-cont {
					border-radius: 5px;
					font-size: 24rpx;
				}
			}

			.live-cont {
				@include df-col();

				&-item {
					max-width: 300rpx;
					background: rgba(51, 51, 51, 0.3);
					border-radius: 5px;
					font-size: 24rpx;
					margin: 10rpx 0;
					color: #fff;
				}
			}
		}

		.chat {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			@include df-row($ai: center);

			&-left {
				&-item {
					@include df-col($jc: center, $ai:center);
					color: #fff;
					font-size: 18rpx;

					image {
						@include build-square(46rpx)
					}
				}
			}

			&-cont {
				flex: 1;
				color: #fff;
			}

			&-right {
				@include df-row($ai: center);

				&-item {
					margin-left: 20rpx;
					@include df-col($jc: center, $ai:center);
					color: #fff;
					font-size: 18rpx;

					image {
						@include build-square(46rpx)
					}
				}
			}
		}

		.btn-wrap {
			@include df-row($jc: space-between);

			button {
				color: #fff;
				height: 80rpx;
				line-height: 80rpx;

				font: {
					size: 28rpx;
					weight: 500;
				}
			}
		}
	}
</style>
